<?php

class Util
{

	public static function get_age($birthday)
	{
	    $age = date('Y', time()) - date('Y', strtotime($birthday)) - 1;
		if (date('m', time()) == date('m', strtotime($birthday))){
			if (date('d', time()) >= date('d', strtotime($birthday))){
				$age++;
			}
		}elseif (date('m', time()) > date('m', strtotime($birthday))){
			$age++;
		}
		
	    return $age + 1;
	}

	public static function uuid($prefix = '')
	{
	    $chars = md5(uniqid(mt_rand(), true));
	    return $prefix.$chars;
	}
	
	public static function ErrorMsg($code,$value)
	{
		$retArray = array(
			'code' => $code,
			'msg' => urlencode($value),
		);
		echo urldecode(CJavaScript::jsonEncode($retArray));
		
		unset($retArray);
			//Yii::app()->session->add('UserID',$primaryKey);
		Yii::app()->end();
		
	}
    

	
	public static function getParam($name,$default)
	{
		$value = Yii::app()->request->getParam($name,$default);

        if(Util::IsEmpty($value))
            return $default;

		
		return $value;
	}
	

	public static function getParamNotEmpty($name)
	{
		$value = Yii::app()->request->getParam($name);

		Util::checkParameterIsEmpty($name, $value);

		return $value;
	}

    public static function getParamNotEmptyDefaultNull($name)
    {
        $value = Yii::app()->request->getParam($name);

        if(Util::IsEmpty($value))
            return "";

        return $value;
    }
	
	public static function ShowMsg($code,$value)
	{
		$retArray = array(
			'code' => $code,
			'msg' => urlencode($value),
			//'uid' =>$primaryKey,
			//'user' => $newUser,
		);

		header('Content-type: application/json');
		echo urldecode(CJavaScript::jsonEncode($retArray));
		
		unset($retArray);
			//Yii::app()->session->add('UserID',$primaryKey);
		Yii::app()->end();
	}
	
	public static function IsEmpty($value)
	{
		return is_null($value) ||  $value=='';
	}
	
	public static function checkParameterIsEmpty($name,$value)
	{
		if(Util::IsEmpty($value))
		{
			throw new Exception($name.ErrorMsgConst::PARAMETER_EMPTY);
		}
		return true;
	}
    
 
	


    public static function OutputSimpleInJsonFormat($code,$msg)
    {
        $retArray = array(
            'code' => $code,
            'msg' => urlencode($msg)
        );


		header('Content-type: application/json');

        echo urldecode(CJavaScript::jsonEncode($retArray));

        unset($retArray);

        Yii::app()->end();

        //unset($retArray);
    }

	public static function OutputObjectInJsonFormat($code,$msg,$value)
	{
		$retArray = array(
			'code' => $code,
			'msg' => urlencode($msg),
			'object' => $value,
		);

		header('Content-type: application/json');
        echo urldecode(CJavaScript::jsonEncode($retArray));
		
		unset($retArray);
		
		Yii::app()->end();
		
		//unset($retArray);
	}
	
	public static function OutputArrayInJsonFormat($code,$msg,$array)
	{
		$retArray = array(
			'code' => $code,
			'msg' => urlencode($msg),
			'count'=>count($array),
			'list' => $array,
		);

		header('Content-type: application/json');
        echo urldecode(CJavaScript::jsonEncode($retArray));
		
		unset($retArray);
		
		Yii::app()->end();
	}
	
	public static function OutputInJsonFormat($code,$msg,$array)
	{
		$retArray = array(
			'code' => $code,
			'msg' => urlencode($msg),
		);
		
		$ret = array_merge($retArray,$array);

		header('Content-type: application/json');
        echo urldecode(CJavaScript::jsonEncode($ret));
		
		unset($retArray);
		
		Yii::app()->end();
	}
	
	
	public static function getCurrentTime()
	{
		return gmdate('Y-m-d H:i:s',time()+3600*8);
	}


	public static function getSession(){
		$sessionid = Util::getParamNotEmpty("sessionid");
	
		$session = Yii::app()->cache->get($sessionid);
		if(!$session){
			Util::ShowMsg(1,"session不存在");
		}
		return $session;
	}
	/**
	*从缓存中取数据
	*
	**/
	public static function setValue($key,$value,$expire=""){
		if(empty($expire))
			Yii::app()->cache->set($key, $value);
		else
			Yii::app()->cache->set($id, $value,$expire);
	}

	//从缓存中取出值
	public static function getValue($key){
		return Yii::app()->cache->get($key);
	}

    //拼接string
    public static function getSerarchStr($str,$key,$searchkey)
    {
        $value = Yii::app()->request->getParam($key);

        if(Util::IsEmpty($value)==false)
        {
            $str = $str." and ".$searchkey." = '".$value."'";
        }

        return $str;

    }

    //直接拼接
    public static function getSerarchStrAdd($str,$key,$value)
    {


            $str = $str." and ".$key." = '".$value."'";


        return $str;

    }

    //直接拼接 in
    public static function getSerarchStrAddIn($str,$key,$value)
    {


        $str = $str." and ".$key." in ".$value."";


        return $str;

    }




    /******************* 输出相关************

    /*
     * 输出成功 信息
     *
     */
    public static function responseMsg($msg)
    {
        $retArray = array(
            'code' => MsgConst::RETURN_CODE_SUCCESS,
            'msg' => urlencode($msg),
        );

        $ret = array_merge($retArray,$retArray);

        header('Content-type: application/json');
        echo urldecode(CJavaScript::jsonEncode($ret));

        unset($retArray);

        Yii::app()->end();

    }

    /*
     * 输出错误信息
     *
     */
    public static function responseErrorMsg($msg)
    {
        $retArray = array(
            'code' => MsgConst::RETURN_CODE_ERROR,
            'msg' => urlencode($msg),
        );

        $ret = array_merge($retArray,$retArray);

        header('Content-type: application/json');
        echo urldecode(CJavaScript::jsonEncode($ret));

        unset($retArray);

        Yii::app()->end();

    }

    /*
     * 输出对象 obj
     *
     */

    public static function responseObj($obj)
    {
        $retArray = array(
            'code' => MsgConst::RETURN_CODE_SUCCESS,
            'msg' => urlencode(MsgConst::RETURN_SUCCESS),
            'data' => $obj,
        );

        header('Content-type: application/json');
        echo urldecode(CJavaScript::jsonEncode($retArray));

        unset($retArray);

        Yii::app()->end();
    }

    /*
     * 输出列表
     */
    public static function responseList($total,$list)
    {
        $retArray = array(
            'code' => MsgConst::RETURN_CODE_SUCCESS,
            'msg' => urlencode(MsgConst::RETURN_SUCCESS),
            'data' => array(
                'total'=>$total,
                'data' => $list,
            )
        );

        header('Content-type: application/json');
        echo urldecode(CJavaScript::jsonEncode($retArray));

        unset($retArray);

        Yii::app()->end();
    }

    /*
     * initSearchSql
     *
     */
    public static function  initSearchSql()
    {
        return "is_delete = 0";
    }

    /*
    * initLimitSql
    *
    */
    public static function  addLimitSql($searchsql)
    {
        $page = Util::getParam("page",1);
        $rows = Util::getParam("rows",5);

        if($page<1){
            throw new Exception("页面不得小于1");
        }


        return $searchsql." limit ".($page-1)*$rows.",".$rows;
    }

    /*
     * 初始化对象
     */
    public static function initObjData($Obj)
    {

        $Obj->created_by = SessionService::getUserInfo();


        Util::initObjDataInfo($Obj);
    }

    public static function initObjDataInfo($Obj)
    {
        $Obj->create_time = DateUtil::getNowTime();
        $Obj->update_time = DateUtil::getNowTime();
        $Obj->is_delete = 0;
    }

    /*
     * 删除对象
     */
    public static function deleteObjData($Obj)
    {

        $Obj->update_time = DateUtil::getNowTime();
        $Obj->is_delete = 1;
    }

    /*
     * 保存对象
     */
    public static function saveObjData($Obj)
    {
        $r1= $Obj->save();

        if (!$r1) {

           // print_r($Obj->errors);



            Yii::log(json_encode($Obj->errors), MsgConst::LOG_TYPE_ERROR, "");

            throw new Exception("保存失败");
        }





    }

    public  static  function  isDelete($obj)
    {
        if($obj->is_delete ==0)
            return false;

        return true;
    }

    //恢复对象
    public static function recoverObjData($Obj)
    {

        $Obj->update_time = DateUtil::getNowTime();
        $Obj->create_time = DateUtil::getNowTime();
        $Obj->is_delete = 0;
        $Obj->created_by = SessionService::getUserInfo();
    }

    //更新对象
    public static function updateObjData($Obj)
    {

        //$Obj->update_time = DateUtil::getNowTime();

        $Obj->updated_by = SessionService::getUserInfo();
        Util::updateObjDataInfo($Obj);

    }

    //更新对象
    public static function updateObjDataInfo($Obj)
    {

        $Obj->update_time = DateUtil::getNowTime();



    }


    //检查对象

    public static function checkExistAndNotDelete($Obj)
    {

        if(empty($Obj))
            throw new Exception("该对象不存在");
        if($Obj->is_delete ==1)
        {


            throw new Exception("该对象已删除");

        }


    }

    public static function checkExist($Obj)
    {

        if(empty($Obj))
            throw new Exception("该对象不存在");

    }

    //log 正常
    public static function log_normal($action,$content)
    {
        Util::write_Log($action,$content,MsgConst::LOG_TYPE_NORMAL);

    }

    //log 错误
    public static function log_error($action,$content)
    {
        Util::write_Log($action,$content,MsgConst::LOG_TYPE_ERROR);

    }

    //log 警告
    public static function log_warning($action,$content)
    {
        Util::write_Log($action,$content,MsgConst::LOG_TYPE_WARNING);


    }


    public static function write_Log($action,$content,$type)
    {
        $url = Yii::app()->controller->id."/".$action->getAction()->id;

        Yii::log($content, $type, $url);

    }

    public static function log_outptut($content)
    {
        $url = Yii::app()->controller->id."/";

        Yii::log($content, MsgConst::LOG_TYPE_NORMAL, $url);

    }

    //检测是否唯恐

    public static function is_empty($value)
    {
        if($value == "" || strlen($value)==0)
            return true;

        return false;
    }


    /*
    * echolog
    *
    */
    public static function echolog($msg)
    {
        echo $msg."<br/>";


    }













}